const { Service } = require("egg");
const expiresIn = 2;


function throwError(ctx, message) {
  ctx.body = {
    code: -221,
    message: message || "Token已失效",
  };
  ctx.status = 200;
}

class AuthService extends Service {
  async create(user) {
    const userId = user.id
    const token = await this.app.jwt.sign(
      {
        userId,
      },
      this.ctx.app.config.jwt.secret,
      {
        expiresIn: `${expiresIn}h`,
      }
    );
    this.ctx.session[userId] = {
      userId,
      account: user.account
    };
    return token;
  }

  async destory(userId) {
    this.ctx.session[userId] = null;
  }

  async getCurrentUser() {
    const token = this.ctx.headers.authorization || "";
    const app = this.ctx.app;
    try {
      return app.jwt.verify(token, app.config.jwt.secret);
    } catch (error) {
      throwError(this.ctx)
    }
  }

  async check() {
    const token = this.ctx.headers.authorization || "";
    if (!token) {
      return false;
    }
    const userId = this.getCurrentUser();
    if (!userId) {
      return false;
    }
    return !!this.ctx.session[userId];
  }
}

module.exports = AuthService;
